//
//  UIView+function.m
//  NewsReader
//
//  Created by 杨乐 on 16/4/29.
//  Copyright © 2016年 GaoSir_. All rights reserved.
//

#import "UIView+function.h"

@implementation XibCache{
    NSMutableDictionary *xibCell;
}

+ (id)shared{
    static XibCache * sSharedInstance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sSharedInstance = [[XibCache alloc] init];
    });
    return sSharedInstance;
}

- (instancetype)init{
    if (self = [super init]) {
        xibCell = [NSMutableDictionary dictionary];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(memoryWarning) name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
    }
    return self;
}

- (void)memoryWarning{
    pr(@"内存警告，清空xibCache");
    [xibCell removeAllObjects];
}

/** 该方法可以集成iPad */
- (UIView *)getViewKey:(NSString *)key atIndex:(int)index{
    UIView * view;
    if (xibCell[key]) {
        UINib * nib = xibCell[key];
        view = [nib instantiateWithOwner:nil options:nil][index];
    }else{
        UINib *nib = [UINib nibWithNibName:key bundle:nil];
        view = [nib instantiateWithOwner:nil options:nil][index];
        [xibCell setObject:nib forKey:key];
    }
    return view;
}

@end

@implementation UIView (function)

+ (instancetype)initWithXIB:(NSString *)name{
    return [UIView initWithXIB:name atIndex:0];
}

+ (instancetype)initWithXIB:(NSString *)name atIndex:(int)index{
    UIView * view = [[XibCache shared] getViewKey:name atIndex:index];
    return view;
}

+ (instancetype)xib{
    return [[XibCache shared] getViewKey:NSStringFromClass(self) atIndex:0];
}

+ (instancetype)xibIndex:(int)index{
    return [[XibCache shared] getViewKey:NSStringFromClass(self) atIndex:index];
}

@end
